var express = require('express')
	  , http = require('http')
	  , session = require('express-session')
	  , app = express()
	  , server = http.createServer(app);

	var bodyParser = require('body-parser');

	// fabicon
	//var favicon = require('serve-favicon');
	//app.use(favicon('./images/favicon.ico'));

	app.use(session({secret: 'alive-story',
					proxy: true,
					resave: true,
					saveUninitialized: true}));
	app.use(bodyParser.json() );       // to support JSON-encoded bodies
	app.use(bodyParser.urlencoded({     // to support URL-encoded bodies
	  extended: true
	})); 

	var multer = require('multer'); 
	app.use(multer()); // for parsing multipart/form-data

	app.use(require('express-domain-middleware')); // for error handling

	// read config file
	global.config = require('./configs/config');
	// add setting values
	function adjustDbSettings(config)
	{

		if(! ('multipleStatements' in config))
			config['multipleStatements'] = true;	// for stored procedure output param

		if(! ('connectionLimit' in config))
			config['connectionLimit'] = 20;

		if(! ('waitForConnections' in config))
			config['waitForConnections'] = true;

		if(! ('autoReconnect' in config))
			config['autoReconnect'] = true;

		if(! ('useConnectionPooling' in config))
			config['useConnectionPooling'] = true;

		if(! ('reconnectDelay' in config))
			config['reconnectDelay'] = 500;

		if(! ('maxReconnectAttempts' in config))
			config['maxReconnectAttempts'] = 25;

		if(! ('keepAlive' in config))
			config['keepAlive'] = true;

		if(! ('keepAliveInterval' in config))
			config['keepAliveInterval'] = 30000;

	}

	adjustDbSettings(global.config.database.master);
	adjustDbSettings(global.config.database.replica);
	adjustDbSettings(global.config.database.log);


	var MySQLConnectionManager = require('mysql-connection-manager'); // for mysql db HA , pool
	global.master_db = new MySQLConnectionManager(global.config.database.master);
	global.replica_db = new MySQLConnectionManager(global.config.database.replica);
	global.log_db = new MySQLConnectionManager(global.config.database.log);

	/*******************************************************************************************/

	var lastDeviceId=0;
	var deviceCount=1000;
	var totalCount = 0;

	var isStart = false;
	var isEnd = false;

	var workHour = (new Date()).getHours();

	var filePath = '/home/ec2-user/nodejs/log/timezonePush_'+workHour+'.log';
	//var filePath = 'd://tmp/'+workHour+'.log';


	function setWorkFinished(callback , targetExist)
	{
		// workhour push 종료되었다고 마킹 - 변경하니까 master
		global.master_db.connection.getConnection(function(err,connection)
		{
			if(err) throw err;

			var input_param = [workHour];
			var sql = "call manage_setTimezonePushFinished(?)";	
			var query = connection.query(sql, input_param , function (err, rows) 
			{
				connection.release();
				if(err) throw err;

				if(targetExist)
				{
					var d = new Date();
					var timestring = d.getFullYear()+"-"+(d.getMonth() + 1)+"-"+d.getDate()+" "+d.getHours()+":"+d.getMinutes()+":"+d.getSeconds();

					var msg = "PUSH FINISHED accum count : " + totalCount;

					// 종료시에는 기존파일에 더함.
					require('fs').appendFile(filePath, '['+timestring+'] ' + msg +'\r\n', function(err) {
							if(err) throw err;

							callback();
					});
				}
				else
				{
					callback();
				}
		
			});
		});
	}


	function appendFile(str)
	{
		var d = new Date();
		var timestring = d.getFullYear()+"-"+(d.getMonth() + 1)+"-"+d.getDate()+" "+d.getHours()+":"+d.getMinutes()+":"+d.getSeconds();

		require('fs').appendFile(filePath, '['+timestring+'] ' + str+'\r\n', function(err) {
				if(err) throw err;
		});
	}


	var async = require('async');

	async.whilst(
		function () { return !isEnd;},
		function (callback) {

			global.replica_db.connection.getConnection(function(err,connection)
			{
				if(err)
				{
					setTimeout(callback, 1000); // 에러?  1초 쉰다.
					return;
				}

				var input_param = [workHour , lastDeviceId , deviceCount];
				var sql = "call manage_getTimezonePushKey(?,?,?)";
				var query = connection.query(sql, input_param , function (err, rows) 
				{
					connection.release();
					if(err)
					{
						setTimeout(callback, 1000); // 에러?  1초 쉰다.
						return;
					}

					var list  = rows[0];
					var message = rows[1][0].message;
					var articleId = rows[1][0].articleId;

					if(list.length == 0)
					{

						isEnd = true;

						// 작업을 했을 경우
						if(totalCount > 0)
							setWorkFinished(callback , true);
						else
							setWorkFinished(callback , false);
					}
					else
					{

						// 시작할 때 - 대상항목이 있을 경우
						if(!isStart)
						{
							isStart = true;

							var d = new Date();
							var timestring = d.getFullYear()+"-"+(d.getMonth() + 1)+"-"+d.getDate()+" "+d.getHours()+":"+d.getMinutes()+":"+d.getSeconds();

							var str = 'MESSAGE : '+message+'\r\n';
							str += '['+timestring+'] workHour [' + workHour + '] PUSH STARTED\r\n';

							// 시작할 때는 생성
							require('fs').writeFile(filePath, str , function(err) {
									if(err) throw err;

							});

						}

						lastDeviceId = list[list.length-1].deviceId; 

						appendFile('last deviceId : ' + lastDeviceId + ', count : ' + list.length , null);
						console.log('last deviceId : ' + lastDeviceId + ', count : ' + list.length);
						
						// 푸시 메시지 만든다.
						var pushList = [];
						for(var i = 0 ; i < list.length ; i ++)
						{

							var pushInfo = {};

							// 모든 푸시 공통 (token , endpointArn , appId , badge , msgid , msgType)
							pushInfo = list[i];
						
							pushInfo.message = message;

							pushInfo.sound = true; //사운드 

							// article 정보가 있을 때.
							if(articleId != null && articleId != '')
							{
								pushInfo.msgType=100;	// 해당 article로 점프한다 (100으로 세팅해야 하는데 일단 아이폰에서 점프가능한 6으로 세팅)
								pushInfo.articleId=articleId;
							}

							pushList[i] = pushInfo;

							appendFile('['+totalCount+'] ['+i+'] ' + list[i].countryCode +',' + list[i].deviceId + ',' + list[i].appId , null);
							console.log('['+totalCount+'] ['+i+'] ' + list[i].countryCode +',' + list[i].deviceId + ',' + list[i].appId);

							// total 카운트 하나 늘림.
							totalCount ++;

						}


						// 푸시 날린다.
						var pushFunction = require('./routes/v0.7/functions/cbPush');
						pushFunction(pushList , callback);


					} // list.length > 0

				}); // replica select query

			}); // replica connection


		},
		function (err) {
			console.log("accum count : " + totalCount);
			process.exit(1);
		}
	);






